<?php
namespace app\admin\controller\auth;

use app\common\controller\AdminBaseController;
use app\common\model\auth\GroupModel;
use app\common\model\auth\RuleModel;
use app\common\model\SiteModel;
use app\common\traits\adminTraits;
use app\common\traits\selectPageTraits;
use think\facade\Config;

class GroupController extends AdminBaseController
{
    /**
     * 需要鉴权的方法,但需要登录
     * @var array
     */
    protected $needRight = [];

    use adminTraits;
    use selectPageTraits;

    /**
     * 初始化方法
     */
    public function __construct()
    {
        parent::__construct();
        $this->model = new GroupModel();
    }

    /**
     * 用户组授权
     */
    public function setRule(){
        if($this->request->isAjax()){
            $groupId = $this->request->param('group_id/d');
            $rules = $this->request->param('rules');
            if($groupId<=0) $this->error('请选择角色');
            $this->model->where('id',$groupId)->setField('rules',$rules);
            $this->success('操作成功！');
        }
        $ruleModel = new RuleModel();
        $groupId = $this->request->param('group_id/d');
        if($this->sessionKey=='site'){
            $siteLevel = SiteModel::where('id',$this->loginInfo['site_id'])->value('site_level');
            $ruleIds = Config::get('auth.site_level.'.$siteLevel);
        }
        $rulelist = $ruleModel->getList(); //获取所有权限列表
        $rules = $this->model->where('id', $groupId)->value('rules'); //获取该角色组拥有权限
        $rules = empty($rules) ? [-1] : explode(',', $rules);
        $rule = [];
        foreach($rulelist as $v){
            if($this->sessionKey=='site' && !in_array($v['id'],$ruleIds)) continue;
            $checked = in_array($v['id'], $rules) ? true : false;
            $rule[] = ['id' => $v['id'], 'pid' => $v['pid'], 'title' => $v['title'], 'checked' => $checked, 'open' => true];
        }
        $groupList = $this->getlist();
        $this->assign('group_list',$groupList);
        $this->assign('rule',$rule);
        return $this->fetch();
    }
}
